package com.hc.comm.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;

import org.apache.log4j.Logger;


public class XssWhiteListConstant {

	private Logger logger = Logger.getLogger(XssWhiteListConstant.class);
	private static XssWhiteListConstant instance;

	private Set<String> uriSet = new HashSet<String>();
	private static String xssWhiteListFilePath = "xss-white-list.txt";

	public static XssWhiteListConstant getInstance() {
		if (instance == null) {
			synchronized (XssWhiteListConstant.class) {
				if (instance == null) {
					instance = new XssWhiteListConstant();
					instance.init();
				}
			}
		}
		return instance;
	}

	/**
	 * 初始化需要增加缓存的URL列表
	 */
	private void init() {
		BufferedReader br = null;
		try {
			InputStream is = XssWhiteListConstant.class.getClassLoader()
					.getResourceAsStream(xssWhiteListFilePath);
			if (is != null) {
				br = new BufferedReader(new InputStreamReader(is));
				String line;
				while ((line = br.readLine()) != null) {
					line = line.trim();
					uriSet.add(line);
				}
				br.close();
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				}
			}
		}
	}

	/**
	 * 判断传进来的uri是否在禁止缓存的uri列表里面
	 * 
	 * @param uri
	 * @return URI列表中是否包含指定URI
	 */
	public boolean contains(String uri) {
		for (String line : uriSet) {
			if (uri.matches(line)) {
				return true;
			}
		}
		return false;
	}

	public static void main(String[] args) {
		XssWhiteListConstant constant = XssWhiteListConstant.getInstance();
		System.out.println(constant.contains("/tuiguang/QQCbRedirect"));
	}

}
